#include <stdio.h>
#include <time.h>
#include "h/test.h"
#include <string.h>
#include <stdlib.h>

#define ARSIZE 1000

int main(void)
{
    double numbers[ARSIZE];
    double value;
    const char * file ="number.dat";
    int i;
    long pos;
    FILE *fp;

    for (i=0; i<ARSIZE; ++i) {
        numbers[i] = 100.0 *i + 1.0 / (i+1);
    }

    if ((fp = fopen(file, "wb")) == NULL) {
        fprintf(stderr, "Could not open %s for output.\n", file);
        exit(EXIT_FAILURE);
    }

    fwrite(numbers, sizeof(double), ARSIZE, fp);

    if (ferror(fp)) {
        fprintf(stderr, "Error in writing file %s.\n", file);
        exit(EXIT_FAILURE);
    }

    if (fclose(fp) == EOF) {
        fprintf(stderr, "writing file %s close failed.\n", file);
        exit(EXIT_FAILURE);
    }

    //start red
    //for unix "rb" equal "r"; for posix use "rb" recommend.
    if ((fp = fopen(file, "rb")) == NULL) {
        fprintf(stderr, "Could not open %s for random access.\n", file);
        exit(EXIT_FAILURE);
    }

    printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);
    while (scanf("%d",&i) == 1 && i>=0 && i<ARSIZE) {
        pos = (long)i * sizeof(double);
        fseek(fp, pos, SEEK_SET);
        fread(&value, sizeof(double), 1, fp);
        printf("The value there is %f.\n", value);

        printf("Next index (out of range to quit):\n");
    }

    return 0;
}

